<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select
          v-model="queryParams.orderType"
          placeholder="订单类型"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="订单状态"
          style="width: 240px"
          clearable
        >
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" style="margin-bottom: 5px"></right-toolbar>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column label="序号" type="index" width="40" align="center" fixed="left"/>
      <el-table-column label="订单编号" prop="orderId" width="115" align="center" fixed="left"/>
      <el-table-column label="订单类型" prop="orderType" width="80" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_type" :value="scope.row.orderType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="orderStatus" width="80" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单押金(元)" prop="orderDeposit" width="75" align="center"/>
      <el-table-column label="押金支付状态" prop="depositPayStatus" width="80" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_status" :value="scope.row.depositPayStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="开始计费时间" align="center" prop="beginTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="停止计费时间" align="center" prop="endTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订单时长"
        prop="realDuration"
        width="120"
        align="center"
        :formatter="orderDurationTimeFormatter"
      >
      </el-table-column>
      <el-table-column label="订单费用(元)" prop="orderFee" width="75" align="center"/>
      <el-table-column label="费用支付状态" prop="feePayStatus" width="80" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_status" :value="scope.row.feePayStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="关闭时间" align="center" prop="closedTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.closedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属用户" prop="userId" width="115" align="center"/>
      <el-table-column label="备注" prop="remark" width="115" align="center"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="showOrderDetail(scope.row)"
          >详情
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--          >修改-->
          <!--          </el-button>-->
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" trigger="click">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <!--              <el-dropdown-item command="showModifyOrderStatusDialog">修改订单状态-->
              <!--              </el-dropdown-item>-->
              <el-dropdown-item command="stopCharging">停止计费
              </el-dropdown-item>
              <el-dropdown-item command="closeOrder">关闭订单
              </el-dropdown-item>

              <!--              <el-dropdown-item command="handleAuthUser">分配用户-->
              <!--              </el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="订单详情" :visible.sync="isOrderDetialDialogShow">
      <el-descriptions title="" :column="3" border>
        <el-descriptions-item label="订单编号">{{ selectedOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <dict-tag :options="dict.type.order_type" :value="selectedOrder.orderType"/>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="dict.type.order_status" :value="selectedOrder.orderStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="订单创建时间" :span="3">
          {{ selectedOrder.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="订单押金(元)" :span="1">{{ selectedOrder.orderDeposit }}</el-descriptions-item>
        <el-descriptions-item label="押金支付状态" :span="2">
          <dict-tag :options="dict.type.pay_status" :value="selectedOrder.depositPayStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="开始计费时间" :span="1">
          {{ selectedOrder.beginTime }}
        </el-descriptions-item>
        <el-descriptions-item label="停止计费时间" :span="1">
          {{ selectedOrder.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="订单时长" :span="1">{{
            formatDurationTime(selectedOrder.realDuration)
          }}
        </el-descriptions-item>
        <el-descriptions-item label="订单费用(元)" :span="1">{{ selectedOrder.orderFee }}</el-descriptions-item>
        <el-descriptions-item label="费用支付状态" :span="2">
          <dict-tag :options="dict.type.pay_status" :value="selectedOrder.feePayStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="订单关闭时间" :span="3">
          {{ selectedOrder.closedTime }}
        </el-descriptions-item>
        <el-descriptions-item label="所属用户" :span="3">{{ selectedOrder.userId }}</el-descriptions-item>
        <el-descriptions-item label="所属码头" :span="1">{{ selectedOrder.wharfName }}</el-descriptions-item>
        <el-descriptions-item label="所属船只编号" :span="1">{{ selectedOrder.boatCode }}</el-descriptions-item>
        <el-descriptions-item :span="1"></el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ selectedOrder.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog title="修改订单状态" :visible.sync="isModifyOrderStatusDialogShow" width="600px">
      <el-form ref="modifyOrderForm" :model="selectedOrderForModifyOrderStatus" label-width="80px">
        <el-form-item label="订单编号">
          <el-input v-model="selectedOrderForModifyOrderStatus.orderId" disabled></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select
            v-model="selectedOrderForModifyOrderStatus.orderStatus"
            placeholder="订单状态"
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
       <el-button @click="isModifyOrderStatusDialogShow = false">取 消</el-button>
       <el-button type="primary" @click="modifyOrderStatus">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  closeOrder,
  listJishiOrder,
  listTaocanOrder,
  modifyJishiOrder,
  modifyTaocanOrder,
  stopCharging
} from "@/api/system/order";

import store from '@/store'

export default {
  name: "OrderManagement",
  dicts: ['order_type', 'order_status', 'pay_status'],
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: "0", //订单类型
        orderStatus: undefined, //订单状态
      },
      // 显示搜索条件
      showSearch: true,
      // 订单表格数据
      orderList: [],
      // 总条数
      total: 0,
      // 遮罩层
      loading: true,
      // 日期范围
      dateRange: [],
      isOrderDetialDialogShow: false, //是否显示订单详情对话框
      isModifyOrderStatusDialogShow: false, //是否显示修改订单状态的对话框
      selectedOrder: {}, //选中的订单
      selectedOrderForModifyOrderStatus: {}, //为了修改订单状态而选中的订单
      orderStatus: "4",
    }
  },
  created() {
    this.scenicId = store.getters.scenicId;
    if (this.scenicId) {
      this.getList();
    } else {
      this.$modal.msgError("景区id为空，获取订单列表失败！");
    }

  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      if (this.scenicId) {
        this.loading = true;
        this.queryParams.scenicId = this.scenicId;
        if (this.queryParams.orderType === "0" || this.queryParams.orderType === 0) { //查询计时计费订单列表
          listJishiOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
              this.orderList = response.rows;
              this.total = response.total;
              this.loading = false;
            }
          );
        } else if (this.queryParams.orderType === "1" || this.queryParams.orderType === 1) { //查询套餐计费订单列表
          listTaocanOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
              this.orderList = response.rows;
              this.total = response.total;
              this.loading = false;
            }
          );
        }
      } else {
        this.$modal.msgError("景区id为空，获取订单列表失败！");
      }
    },
    orderDurationTimeFormatter(row, column) {
      // console.log("orderDurationTimeFormatter: ", row, column);
      return this.formatDurationTime(row.realDuration);
    },
    formatDurationTime(mss) {
      let timeStr = "0";
      let d = parseInt(mss / (1000 * 60 * 60 * 24));
      let h = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let m = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
      let s = parseInt((mss % (1000 * 60)) / 1000);

      if (d > 0) {
        timeStr = d + "天" + this.formatStr(h) + "小时" + this.formatStr(m) + "分" + this.formatStr(s) + "秒";
      } else if (h > 0) {
        timeStr = h + "小时" + this.formatStr(m) + "分" + this.formatStr(s) + "秒";
      } else if (m > 0) {
        timeStr = m + "分" + this.formatStr(s) + "秒";
      } else if (s > 0) {
        timeStr = this.formatStr(s) + "秒";
      }
      // console.log("timeStr: ", timeStr);
      return timeStr;
    },
    formatStr(t) {
      return t < 10 ? '0' + t : t.toString()
    },
    /** 查看订单详情 */
    showOrderDetail(row) {
      this.isOrderDetialDialogShow = true;
      this.selectedOrder = row;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {

    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "showModifyOrderStatusDialog":
          this.showModifyOrderStatusDialog(row);
          break;
        case "handleAuthUser":
          // this.handleAuthUser(row);
          break;
        case "closeOrder":
          this.closeOrder(row);
          break;
        case "stopCharging":
          this.stopCharging(row);
          break;
        default:
          break;
      }
    },
    /**
     * 显示修改订单状态的对话框。
     * @param row
     */
    showModifyOrderStatusDialog(row) {
      // console.log("showModifyOrderStatusDialog row: ", row)
      let clonedOrder = _.cloneDeep(row);
      // console.log("showModifyOrderStatusDialog row: ",row)
      this.selectedOrderForModifyOrderStatus = Object.defineProperty(clonedOrder, "orderStatus", {
        value: clonedOrder.orderStatus.toString(),
        writable: true,
        enumerable: true,
        configurable: true
      })
      // console.log("showModifyOrderStatusDialog this.selectedOrderForModifyOrderStatus: ",this.selectedOrderForModifyOrderStatus)
      // console.log("showModifyOrderStatusDialog row: ",row)
      this.isModifyOrderStatusDialogShow = true;
    },
    /**
     * 后台主动停止计费。
     * @param row
     */
    stopCharging(row) {
      console.log("stopCharging row: ", row)

      //订单状态。0：待付款，1：待使用，2：使用中，3: 已关闭，4：已完成
      let orderStatus = row.orderStatus;

      //先判断当前订单状态是否处于使用中
      if (orderStatus === 2) {
        //再判断当前订单是否已经开始计费
        let beginTime = row.beginTime;
        if (beginTime) { //订单已经开始计费，且还未结束计费。(如果订单已经开始计费，且状态仍然处于使用中则一定还未停止计费)
          this.$modal.confirm("是否确认停止当前订单的计费？").then(res => {
            console.log("确认停止当前订单的计费!")

            let requestData = {
              orderId: row.orderId,
              orderType: row.orderType, //订单类型。0：计时收费订单，1：套餐收费订单，2：拼团订单。
              orderStatus
            }

            //主动停止计费
            stopCharging(requestData).then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess("停止计费成功！")

                this.getList();
              } else {
                this.$modal.msgError("停止计费失败！")
              }

            }).catch(err => {

            })
          }).catch(() => {
            console.log("取消停止当前订单的计费!")
          })

        } else {
          this.$modal.msgWarning("当前订单还未开始计费，因此无法停止计费！");
        }
      } else {
        this.$modal.msgWarning("当前订单状态未处于使用中，无法停止计费！");
      }

    },
    /**
     * 后台主动关闭指定订单。
     * 注意：
     * 1，后台能主动关闭的订单类型：
     *   (1) 处于使用中且还未开始计费的订单，此类型的订单已完成押金支付，且已扫码确认上船，但可能由于游客滑屏解锁船只失败，比如船锁坏了打不开或其他原因导致船无法使用，
     *   当前订单无法进行下去也无法结束，因此只能在后台手动关闭此订单。
     *   (2) 已结束计费但仍存在待支付费用(如计时订单计时费用和套餐订单超时费用)的订单(此时订单也处于待付款状态)，这种类型的订单后台主动给其关闭的目的通常是为了让特殊用户免费游玩的，订单关闭后押金也会主动退还。
     * 2，后台主动关闭订单后，也会主动退还用户已支付的押金(如果有支付过)，且用户还未支付的订单费用也不用支付了；
     */
    closeOrder(row) {
      console.log("closeOrder row: ", row)

      //订单状态。0：待付款，1：待使用，2：使用中，3: 已关闭，4：已完成
      let orderStatus = row.orderStatus;

      if (orderStatus === 3 || orderStatus === 4) {
        this.$modal.msgWarning("当前订单已关闭或已完成，无需关闭！");
      } else if (orderStatus === 1) {
        this.$modal.msgWarning("无法关闭待使用中的订单！");
      } else if (orderStatus === 2) { //使用中
        let beginTime = row.beginTime;
        if (!beginTime) { //确保订单还未开始计费
          this.$modal.confirm("是否确认关闭当前订单？注意：订单被关闭后用户已支付的押金及费用将会全额原路退回，且待支付的费用(如果有的话)也将不再收取，请谨慎操作！").then(res => {
            let requestData = {
              orderId: row.orderId,
              orderType: row.orderType, //订单类型。0：计时收费订单，1：套餐收费订单，2：拼团订单。
              orderStatus
            }

            //关闭使用中且还未开始计费的订单
            closeOrder(requestData).then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess("订单关闭成功！")

                this.getList();
              } else {
                this.$modal.msgError("订单关闭失败！")
              }

            }).catch(err => {

            })
          }).catch(err => {

          })
        } else { //订单已开始计费且还未停止计费，不支持关闭，可先停止计费，然后再关闭
          this.$modal.msgWarning("当前订单还在计费中，无法关闭！");
        }
      } else if (orderStatus === 0) { //关闭已停止计费，且还存在待支付费用的订单
        let orderFee = row.orderFee;
        let endTime = row.endTime;
        if (endTime && orderFee >= 0) { //当前订单已停止计费，且还存在待支付费用
          this.$modal.confirm("是否确认关闭当前订单？注意：订单被关闭后用户已支付的押金及费用将会全额原路退回，且待支付的费用(如果有的话)也将不再收取，请谨慎操作！").then(res => {
            let requestData = {
              orderId: row.orderId,
              orderType: row.orderType, //订单类型。0：计时收费订单，1：套餐收费订单，2：拼团订单。
              orderStatus
            }

            //主动关闭订单
            closeOrder(requestData).then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess("订单关闭成功！")

                this.getList();
              } else {
                this.$modal.msgError("订单关闭失败！")
              }

            }).catch(err => {

            })
          }).catch(err => {

          })
        }
      }
    },

    /**
     * 修改订单状态。
     */
    modifyOrderStatus() {
      this.isModifyOrderStatusDialogShow = false;

      console.log("modifyOrderStatus this.selectedOrderForModifyOrderStatus: ", this.selectedOrderForModifyOrderStatus)
      if (this.selectedOrderForModifyOrderStatus.orderType === 0) { //计时计费订单
        modifyJishiOrder(this.selectedOrderForModifyOrderStatus).then(res => {
          this.$modal.msgSuccess("修改成功");

          this.getList();
        })
      } else if (this.selectedOrderForModifyOrderStatus.orderType === 1) { //套餐计费订单
        modifyTaocanOrder(this.selectedOrderForModifyOrderStatus).then(res => {
          this.$modal.msgSuccess("修改成功");

          this.getList();
        })
      }
    },
    handleBoatInfoTableRowClick(row, column, event) {
      console.log("handleBoatInfoTableRowClick: ", row, column, event);
    }
  }
}
</script>

<style scoped>

</style>
